'''
Created on 2011-10-29

@author: jiangxd
'''
'''
Created on 2011-10-29

@author: jiangxd
'''
import urllib
import json

class UrlOpener(urllib.FancyURLopener):
	version = "py-gtranslate/1.0"

class InvalidLanguage(Exception): pass

class Translator2:
#	base_uri = "http://ajax.googleapis.com/ajax/services/language/translate"
	base_uri = "https://www.googleapis.com/language/translate/v2?parameters"

	default_params = {'v': '1.0'}
	def translate(self,src, to, phrase):
		args = self.default_params.copy()
		args.update({
					'langpair': '%s%%7C%s' % (src, to),
					'q': urllib.quote_plus(phrase),
	        })
		argstring = '%s' % ('&'.join(['%s=%s' % (k,urllib.urlencode(v)) for (k,v) in args.iteritems()]))
		try:
			resp = json.load(UrlOpener().open('%s?%s' % (self.base_uri, argstring)))
			return resp['responseData']['translatedText']
		except:
			return phrase

